package v1

import (
	"gin-example/models"
	"gin-example/pkg/e"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
	"log"
	"net/http"
	"strconv"
)

func GetAllProjects(c *gin.Context) {
	data := make(map[string]interface{})
	code := e.SUCCESS

	data["lists"] = models.GetProjects()

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": data,
	})
}

func AddProject(c *gin.Context) {
	json := make(map[string]string)
	_ = c.BindJSON(&json)

	content := json["content"]
	i18n := json["i18n"]
	show := json["show"]
	if len(show) == 0 {
		show = "0"
	}

	valid := validation.Validation{}
	valid.Required(content, "content").Message("内容不能为空")
	valid.Required(i18n, "i18n").Message("语言不能为空")
	code := e.INVALID_PARAMS
	if !valid.HasErrors() {
		code = e.SUCCESS
		tmp, _ := strconv.Atoi(show)
		models.AddProject(content, i18n, int8(tmp))
	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": make(map[string]string),
	})
}

func UpdateProject(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()
	code := e.INVALID_PARAMS

	if models.ExistProjectByID(id) {
		code = e.SUCCESS
		json := make(map[string]string)
		_ = c.BindJSON(&json)
		content := json["content"]
		show := json["show"]
		tmp, _ := strconv.Atoi(show)
		data := make(map[string]interface{})
		data["content"] = content
		data["show"] = int8(tmp)
		models.UpdateProject(id, data)
	} else {
		code = e.ERROR_NOT_EXIST
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": make(map[string]string),
	})
}

func DeleteProject(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()
	code := e.INVALID_PARAMS
	if models.ExistProjectByID(id) {
		models.DeleteProject(id)
		code = e.SUCCESS
	} else {
		code = e.ERROR_NOT_EXIST
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": make(map[string]string),
	})
}